package com.teamventure.app;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import com.teamventure.app.util.UserData;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class LoginActivity extends Activity {
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
	}
	
	public void tryLogin(View v) {
		Log.d("LoginActivity","Made it to tryLogin");
		
		EditText username = (EditText)findViewById(R.id.username_input);
		EditText password = (EditText)findViewById(R.id.password_input);
		
		if(username.getText().toString().length() > 0 
				&& password.getText().toString().length() > 0) {
			
			HashMap<String,String> params = new HashMap<String,String>();
			params.put("username", username.getText().toString());
			params.put("password", password.getText().toString());
			
			String response = UserData.getUserData().getConnection().sendRequest("login", params);
			
			JSONTokener toke = new JSONTokener(response);
			JSONArray arr = null;
			JSONObject obj = null;
			try {
				arr = new JSONArray(toke);
				obj = arr.getJSONObject(0);
				if(params.get("username").equals((String)obj.get("name"))
						&& params.get("password").equals((String)obj.get("pass"))) {
					UserData.getUserData().setUsername(params.get("username"));
					UserData.getUserData().setPassword(params.get("password"));
					File prefFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+UserData.PREFS_LOC);
					if(!prefFile.isFile()) {
						try{
							prefFile.createNewFile();
							FileWriter fw = new FileWriter(prefFile);
							fw.write(params.get("username"));
							fw.write('\n');
							fw.write(params.get("password"));
						} catch(IOException e) {
							//TODO Do something with the caught exception
						}
					}
					
					startActivity(new Intent(LoginActivity.this, MainActivity.class));
				} else {
					this.displayBadLoginMessage();
				}
			} catch(JSONException e) {
				this.displayBadLoginMessage();
			}
		} else {
			this.displayBadLoginMessage();
		}
	}
	
	private void displayBadLoginMessage() {
		Context context = getApplicationContext();
		Toast toast = Toast.makeText(context, "Invalid information", Toast.LENGTH_SHORT);
		toast.show();
	}
}
